#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'teffy'

'''
@filename manage
@@created on 2018-01-14
@poject:python_flask_demo
@auther:teffy
'''

import os
import sys

COV = None
if os.environ.get('FLASK_COVERAGE'):
    import coverage

    COV = coverage.coverage(branch=True, include='app/*')
    COV.start()

import click

from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell

from app import create_app, db
from app.models import User, Role, Permission, Post, Comment

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)


def make_shell_context():
    return dict(app=app, db=db, User=User, Role=Role, Permission=Permission, Post=Post, Comment=Comment)


manager.add_command('shell', Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)


@manager.command
@click.option('--coverage/--no-coverage', default=False, help='Run tests under code coverage.')
def test(coverage=False):
    """
    Run the unit tests.
    """
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import subprocess
        os.environ['FLASK_COVERAGE'] = '1'
        sys.exit(subprocess.call(sys.argv))

    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version:file://%s/index' % covdir)
        COV.erase()


@manager.command
@click.option('--length', default=25, help='Number of functions to include in the profiler report.')
@click.option('--profile-dir', default=None, help='Directory where profiler data files are saved.')
def profile(lenght=25, profile_dir=None):
    """
    Start the application under the coder profiler.
    :param lenght:
    :param profile_dir:
    :return:
    """
    from werkzeug.contrib.profiler import ProfilerMiddleware
    app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[lenght], profile_dir=profile_dir)
    app.run()

@manager.command
def deply():
    """
    Run deployment tasks.
    :return:
    """
    from flask_migrate import upgrade
    from app.models import User,Role

    upgrade()

    Role.insert_roles()
    User.add_self_follows()

if __name__ == '__main__':
    manager.run()
